package com.woniuxy.user.controller;

import com.woniuxy.commons.entity.User;
import com.woniuxy.commons.service.FeignEscortService;
import com.woniuxy.commons.util.JWTUtil;

import com.woniuxy.commons.util.ResponseResult;
import com.woniuxy.commons.util.ResultStatus;
import com.woniuxy.user.mapper.UserMapper;
import com.woniuxy.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;

@Resource
private FeignEscortService feignEscortService;

@Resource
private UserMapper userMapper;
@Resource
private RedisTemplate<String,Object> redisTemplate;

    //注册
    @PostMapping("/register")
    public ResponseResult register(@RequestBody String userInfo){
        log.info(userInfo.toString());
        ResponseResult responseResult = new ResponseResult();
        boolean res = userService.register(userInfo);

        responseResult.setMsg("注册失败");
        responseResult.setStatus(ResultStatus.FAIL);
        responseResult.setCode(500);
        if (res){
            responseResult.setMsg("注册成功");
            responseResult.setStatus(ResultStatus.SUCCESS);
            responseResult.setCode(200);
        }
        return responseResult;
    }
    //判断是否存在该用户名
    @GetMapping("/isExistUsername/{username}")
    public ResponseResult isExistUsername(@PathVariable("username") String username){
        ResponseResult responseResult = new ResponseResult();
        boolean res = userService.isExistUsername(username);
        responseResult.setMsg("该用户名已存在!");
        responseResult.setStatus(ResultStatus.FAIL);
        responseResult.setCode(500);
        if (res) {
            responseResult.setMsg("该用户名可用");
            responseResult.setStatus(ResultStatus.SUCCESS);
            responseResult.setCode(200);
        }
        return responseResult;
    }
   //根据条件查询用户
    @PostMapping("/isExist")
    public ResponseResult<List<User>> isExist(@RequestBody User user){
        log.info("前端传来的user"+user.toString());
//        String i= user.getStatus();
//        if (i.equals("启用")){
//            user.setStatus(1);
//        }else {
//            user.setStatus(2);
//        }
//        log.info("修改过后的user"+user.toString());
        ResponseResult<List<User>> responseResult = new ResponseResult<>();
        List<User> user1 = userService.isExist(user);
        log.info("修改过后的user"+user1.toString());
        responseResult.setData(user1);
        return responseResult;
    }
     //判断是否存在该手机号（已验证）
    @GetMapping("/isExistPhone/{phone}")
    public ResponseResult isExistPhone(@PathVariable("phone")String phone){
        ResponseResult responseResult = new ResponseResult();
        boolean res = userService.isExistPhone(phone);
        responseResult.setMsg("该手机号已存在");
        responseResult.setStatus(ResultStatus.FAIL);
        responseResult.setCode(500);
        if (res){
            responseResult.setMsg("该手机号不存在");
            responseResult.setStatus(ResultStatus.SUCCESS);
            responseResult.setCode(200);
        }
        return responseResult;
    }
    //登录(已验证)
    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user, HttpServletResponse response) {
        log.info(user.toString());
        //用用户账号作为查询条件去查询用户信息，对比密码是否正确
        int res = userService.login(user);
        ResponseResult responseResult = new ResponseResult();
        if (res == 1){
            //登陆成功
            //生成token，放到响应头中返回给前端
            String token = JWTUtil.generateToken(user.getUsername());

            //refreshToken
            String refreshToken = UUID.randomUUID().toString();

            //放到redis中,并设置refreshToken过期时间，用户在该过期时间内没有做任何一次操作，那么过期后就需要重新登陆
            redisTemplate.opsForValue().set(refreshToken,token, JWTUtil.REFRESH_TOKEN_EXPIRE_TIME, TimeUnit.MILLISECONDS);

            responseResult.setCode(200);
            responseResult.setMsg("登陆成功");
            responseResult.setStatus(ResultStatus.SUCCESS);
            //设置响应头
            response.setHeader("authorization",token);
            response.setHeader("refreshToken",refreshToken);
            //暴露头,暴露两个
            response.setHeader("Access-Control-Expose-Headers","authorization,refreshToken");
        }else if (res == 2){
            responseResult.setCode(401);
            responseResult.setMsg("账号未激活");
            responseResult.setStatus(ResultStatus.LOGIN_FAIL);
        } else if (res == 0) {
            responseResult.setCode(402);
            responseResult.setMsg("账号或者密码错误");
            responseResult.setStatus(ResultStatus.LOGIN_FAIL);
        }
        return responseResult;
    }

    //判断密码是否与原密码相同
    @PostMapping("/isPasswordSame")
    public ResponseResult isPasswordSame(@RequestBody User user){
        ResponseResult responseResult = new ResponseResult();
        boolean res = userService.isPasswordSame(user);
        responseResult.setMsg("该密码与原密码相同");
        responseResult.setStatus(ResultStatus.FAIL);
        responseResult.setCode(500);
        if (res){
            responseResult.setMsg("该密码可用");
            responseResult.setStatus(ResultStatus.SUCCESS);
            responseResult.setCode(200);
        }
        return responseResult;
    }
    //修改密码
    @PutMapping("/changePassword")
    public ResponseResult changePassword(@RequestBody User user) {
        ResponseResult responseResult = new ResponseResult();
        boolean res = userService.changePassword(user);
        responseResult.setMsg("密码修改失败");
        responseResult.setStatus(ResultStatus.FAIL);
        responseResult.setCode(500);
        if (res) {
            responseResult.setMsg("密码修改成功");
            responseResult.setStatus(ResultStatus.SUCCESS);
            responseResult.setCode(200);
        }
        return responseResult;
    }
    //鉴权
    //参数1：用户
    //参数2：方法上的权限
    @GetMapping("/perms/{username}/{perms}")
    public ResponseResult hasPerms(@PathVariable("username") String username, @PathVariable("perms") String perms ) {
        ResponseResult responseResult = new ResponseResult();

        List<String> permsList = userService.findPermsByUsername(username);


        //根据用户信息查询出当前用户的所有权限，然后用传进来的权限去一一对比，如果对比上说明当前用户有该权限，否则没有
        log.info(perms);
        //假设用户有以下权限
        //List<String> permsList1 = Arrays.asList("order:find","order:del","order:update");

        for (String value : permsList) {

            if (value.equals(perms)) {
                //有权限
                responseResult.setCode(200);
                responseResult.setMsg("有权限");
                responseResult.setStatus(ResultStatus.SUCCESS);
                responseResult.setData(true);
                return responseResult;
            }
        }
        //for循环正常结束，说明没这个权限
        responseResult.setCode(401);
        responseResult.setMsg("没权限");
        responseResult.setStatus(ResultStatus.FAIL);
        responseResult.setData(false);
        //

        return responseResult;

    }
}

